import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Card, Row, Col, Modal, Input, Spin, Collapse, Tag, Icon, Button, Tooltip } from 'antd';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import MyTreeConfig from '../../components/_public/MyTreeConfig';
import MyEditor from '../../components/_public/MyEditor';

import TreeConfigTable from '../../insideTools/TreeConfigTable';

import { getScreenHeight, myMessage } from '../../utils/formatDataSource';
import Katex from '../../components/_public/Katex';
import QuestionModal from '../Lesson/questions/QuestionModal';

@connect(({ treeConfig2, loading }) => ({
  treeConfig:treeConfig2,
  treeLoading: loading.effects['treeConfig2/list'],
  tagLoading: loading.effects['treeConfig2/getTreeQuesitonsHistory'],
}))
class TreeConfig extends PureComponent {
  state = {
    treeList: [],
    deleteVisible: false,
    editorVisible: false,
    detailInfoLoading: false,
    editorTitle: '添加',
    currentEditorContent: '', // 当前编辑的知识树内容
    treeAction: 1, // 1 添加  2 修改
    currentAddNode: { content: '', key: -1 },
    currentDelNode: { content: '', key: -1 },
    detailInfo: [],
    selectedKeys: [],
    totalKeys: [],
    tags: [],
    inputVisible: false,
    inputValue: '',
    tagChecked: false,
    modalShow: false,
    questiontypeIds: [],
    existIds: [],
    data: [],
    where: 'liti',
    currentQuestiontypeId: 0,
  };

  componentDidMount = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'treeConfig/list',
    }).then(() => {
      this.setState({
        treeList: this.props.treeConfig.treeList,
      });
    });

    dispatch({
      type: 'treeConfig/getFormulaToolbar',
    });

    dispatch({
      type: 'treeConfig/getTotalTags',
    })
      .then(() => {
        this.setState({
          tags: this.props.treeConfig.tags,
        });
      })
      .then(() => {
        const { tags } = this.state;
        dispatch({
          type: 'treeConfig/getTreeQuesitonsHistory',
          payload: {
            versionId: tags[0].id,
          },
        }).then(() => {
          this.setState({
            data: this.props.treeConfig.historyQuestions,
          });
        });
      });
  };
  showDeleteModal = item => {
    this.setState({
      deleteVisible: true,
      currentDelNode: item,
    });
  };
  showEditorModal = (item, action) => {
    const title = this.getEditorTitle(action === '添加' ? item.type + 1 : item.type);
    this.setState({
      currentEditorContent: action === '修改' ? item.content : '',
      treeAction: action === '修改' ? 2 : 1,
      editorTitle: action + title,
      editorVisible: true,
      currentAddNode: item,
    });
  };
  handleOk = item => {
    const { currentDelNode } = this.state;
    this.props
      .dispatch({
        type: 'treeConfig/remove',
        payload: {
          currentId: currentDelNode.id,
          currentType: currentDelNode.type,
        },
      })
      .then(() => {
        const { response } = this.props.treeConfig;
        let newDetailInfo = [];
        if (response.status === 0) {
          newDetailInfo = this.state.detailInfo.filter(d => d.id !== currentDelNode.id);
          myMessage.success('删除成功', 2);
        } else {
          myMessage.error('删除失败', 2);
        }
        this.props
          .dispatch({
            type: 'treeConfig/list',
          })
          .then(() => {
            this.setState({
              treeList: this.props.treeConfig.treeList,
              detailInfo: [...newDetailInfo],
            });
          });
      });
    this.setState({ deleteVisible: false });
  };
  handleCancel = () => {
    this.setState({ deleteVisible: false });
  };
  handleEditorOk = () => {
    const { currentAddNode, treeList } = this.state;
    this.props
      .dispatch({
        type: 'treeConfig/add',
        payload: {
          parentId: currentAddNode.id,
          parentType: currentAddNode.type,
          content: this.state.currentEditorContent,
          action: this.state.treeAction,
        },
      })
      .then(() => {
        const {
          currentAddNode,
          treeAction,
          currentEditorContent,
          selectedKeys,
          totalKeys,
        } = this.state;
        if (treeAction === 2) {
          // 修改
          if (currentAddNode.type === 1 || currentAddNode.type === 2) {
            const value = currentAddNode.viewContent;
            currentAddNode.content = currentEditorContent;
            currentAddNode.viewContent =
              value.substring(0, value.indexOf('-') + 1) + currentEditorContent;
          } else {
            currentAddNode.content = currentEditorContent;
          }
        } else if (treeAction === 1) {
          // 添加
          const { response } = this.props.treeConfig;
          if (response.status === 0) {
            const son = response.data;
            son.uniqueKey = currentAddNode.uniqueKey + '_' + son.id;
            if (currentAddNode.sons) {
              currentAddNode.sons.push(son);
            } else {
              currentAddNode.sons = [son];
            }
            if (currentAddNode.type === 1) {
              son.viewContent = `第${currentAddNode.sons.length + 1}节-${son.content}`;
            }
            totalKeys.push(son.uniqueKey);
            const newSelectedKeys = selectedKeys.filter(s => {
              const sArr = s.split('_');
              const newArr = son.uniqueKey.split('_');
              if (sArr.length === newArr.length) {
                return true;
              } else {
                return false;
              }
            });
            this.setState({
              selectedKeys: newSelectedKeys,
            });
          }
        }
        this.setState({
          treeList: [...treeList],
        });
      });
    this.setState({ editorVisible: false });
  };
  handleEditorCancel = () => {
    this.setState({ editorVisible: false });
  };
  handleCheck = (selectedKeys, totalKeys) => {
    this.setState({
      detailInfoLoading: true,
      selectedKeys,
      totalKeys,
    });
    const detailInfo = [];
    this.saveDetail(this.state.treeList, totalKeys, detailInfo, 0);
    detailInfo.map(d => {
      if (d.type === 4) {
        this.getCommonQuestions(d);
      } else if (d.type === 5) {
        this.getQuestions(d);
      }
    });
    setTimeout(() => {
      this.setState({
        detailInfo,
        detailInfoLoading: false,
      });
    }, 1000);
  };
  saveDetail = (treeList, total, content, parentId) => {
    treeList.map(t => {
      if (total.includes(t.uniqueKey)) {
        if (t.sons) {
          content.push(t);
          this.saveDetail(t.sons, total, content, t.id);
        } else {
          content.push(t);
        }
      }
    });
  };
  getQuestions = (item, page, size) => {
    const params = {
      id: item.id,
    };
    if (page) {
      params.page = page;
      params.size = size;
    }
    this.props
      .dispatch({
        type: 'treeConfig/questions',
        payload: params,
      })
      .then(() => {
        item.questionVoList = this.props.treeConfig.questions;
        if (page) {
          const { detailInfo } = this.state;
          this.setState({ detailInfo: [...detailInfo] });
        }
      });
  };
  getCommonQuestions = (item, page, size) => {
    const params = {
      id: item.id,
    };
    if (page) {
      params.page = page;
      params.size = size;
    }
    this.props
      .dispatch({
        type: 'treeConfig/commonQuestions',
        payload: params,
      })
      .then(() => {
        item.questionVoList = this.props.treeConfig.questions;
        if (page) {
          const { detailInfo } = this.state;
          this.setState({ detailInfo: [...detailInfo] });
        }
      });
  };
  getEditorTitle = type => {
    switch (type) {
      case 1:
        return '章';
      case 2:
        return '节';
      case 3:
        return '知识点';
      case 4:
        return '方法';
      case 5:
        return '题型';
    }
  };
  pageChange = (item, page, size) => {
    this.getQuestions(item, page, size);
  };
  commonPageChange = (item, page, size) => {
    this.getCommonQuestions(item, page, size);
  };
  deleteTableCell = (questionId, where, questiontypeId) => {
    const { data } = this.state;
    const current = data.find(d => d.qtID === questiontypeId);
    if (!current) {
      return;
    }
    if (where === 'liti') {
      current.demoQuestions = current.demoQuestions.filter(q => q.id !== questionId);
    }
    if (where === 'xiti') {
      current.testQuestions = current.testQuestions.filter(q => q.id !== questionId);
    }
    this.setState({
      data: [...data],
    });
  };
  updateQuestions = (question, isCommon) => {
    this.props
      .dispatch({
        type: 'treeConfig/updateQuestion',
        payload: {
          question: JSON.stringify(question),
          type: isCommon,
        },
      })
      .then(() => {
        this.handleCheck(this.state.selectedKeys, this.state.totalKeys);
      });
  };
  setDemoClick = (questionId, type) => {
    const param = {
      questionId,
    };
    if (type) {
      param.type = type;
    }
    this.props.dispatch({
      type: 'treeConfig/updateDemoQuestion',
      payload: param,
    });
  };

  handleClose = removedTag => {
    const tags = this.state.tags.filter(tag => tag.id !== removedTag.id);
    this.setState({ tags });
  };
  showInput = () => {
    this.setState({ inputVisible: true }, () => this.input.focus());
  };
  handleInputChange = e => {
    this.setState({ inputValue: e.target.value });
  };
  handleInputConfirm = () => {
    const state = this.state;
    const inputValue = state.inputValue;
    let tags = state.tags;
    if (inputValue && tags.indexOf(inputValue) === -1) {
      this.props
        .dispatch({
          type: 'treeConfig/saveTag',
          payload: {
            content: inputValue,
          },
        })
        .then(() => {
          if (this.props.treeConfig.tagSaveStatus) {
            const newObj = {
              id: tags.length + 1,
              content: inputValue,
            };
            tags = [...tags, newObj];
          }
          this.setState({
            tags,
            inputVisible: false,
            inputValue: '',
          });
        });
    }
  };
  saveInputRef = input => (this.input = input);

  setCheckedTag = (checked, tag) => {
    const { tags } = this.state;

    tags.map(t => {
      if (t.id === tag.id) {
        if (t.checked) {
          return;
        }
        t.checked = checked;
      } else {
        t.checked = false;
      }
    });

    this.props
      .dispatch({
        type: 'treeConfig/getTreeQuesitonsHistory',
        payload: {
          versionId: tag ? tag.id : 0,
        },
      })
      .then(() => {
        setTimeout(() => {
          this.setState({
            data: this.props.treeConfig.historyQuestions,
            tags: [...tags],
          });
        }, 500);
      });
  };

  showQuestionModal = (where, currentQuestiontypeId) => {
    const { data } = this.state;
    const current = data.find(d => d.qtID === currentQuestiontypeId);
    let existIds = [];
    if (current) {
      if (where === 'liti') {
        existIds = current.demoQuestions.map(q => q.id);
      } else {
        existIds = current.testQuestions.map(q => q.id);
      }
    }
    this.setState({
      modalShow: true,
      where,
      currentQuestiontypeId,
    });
    setTimeout(() => {
      this.questionModal.getServerQuestions({ existIdStr: existIds.join(',') });
    }, 100);
  };
  okModal = questions => {
    const { data, where, currentQuestiontypeId } = this.state;
    const current = data.find(d => d.qtID === currentQuestiontypeId);
    if (!current) {
      data.push({
        qtID: currentQuestiontypeId,
        demoQuestions: where === 'liti' ? questions : [],
        testQuestions: where === 'xiti' ? questions : [],
      });
    } else {
      if (where === 'liti') {
        current.demoQuestions.push(...questions);
      } else if (where === 'xiti') {
        current.testQuestions.push(...questions);
      }
    }
    // data.sort((a, b) => {
    //   if(a.refId === b.refId) {
    //     return a.id - b.id;
    //   }
    //   else {
    //     return a.refId - b.refId;
    //   }
    // });
    this.setState({
      data: data,
      modalShow: false,
    });
  };
  getQuestions = (questiontypeId, where) => {
    const result = {
      total: 0,
      data: [],
      questiontypeId: questiontypeId,
      where: where,
    };
    const { data } = this.state;
    const current = data.find(d => d.qtID === questiontypeId);
    if (!current) {
      return result;
    }
    if (where === 'liti') {
      result.total = current.demoQuestions.length;
      result.data = current.demoQuestions;
    } else if (where === 'xiti') {
      result.total = current.testQuestions.length;
      result.data = current.testQuestions;
    }
    setTimeout(() => {
      this.setState({
        data,
      });
    }, 500);
    return result;
  };

  moveQuestions = (newQuestions, where, questiontypeId) => {
    const { data } = this.state;
    const current = data.find(d => d.qtID === questiontypeId);
    if (!current) {
      return;
    }
    if (where === 'liti') {
      current.demoQuestions = newQuestions;
    } else if (where === 'xiti') {
      current.testQuestions = newQuestions;
    }
    this.setState({ data: [...data] });
  };

  saveTreeConfig = () => {
    console.log(this.state.treeList);
    const { data, tags } = this.state;
    const one = tags.find(t => t.checked);
    this.props.dispatch({
      type: 'treeConfig/saveTreeQuestion',
      payload: { tagId: one.id, data: data },
    });
  };
  moveTree = params => {
    this.props
      .dispatch({
        type: 'treeConfig/moveTreeItem',
        payload: params,
      })
      .then(() => {
        console.log('更新成功');
      });
  };
  upData = data => {
    this.setState({
      treeList: data,
    });
  };
  updateTreeMove = data => {
    console.log(data);
    const { treeList, totalKeys } = this.state;
    this.setState({
      detailInfoLoading: true,
    });
    const detailInfo = [];
    this.saveDetail(treeList, totalKeys, detailInfo, 0);
    this.props
      .dispatch({
        type: 'treeConfig/moveTrees',
        payload: {
          treeList: data,
        },
      })
      .then(() => {
        setTimeout(() => {
          this.setState({
            detailInfo,
            detailInfoLoading: false,
            treeList: [...data],
          });
        }, 500);
      });
  };

  render() {
    const { CheckableTag } = Tag;
    const { tags, inputVisible, inputValue } = this.state;
    const { toolBar } = this.props.treeConfig;
    const { treeLoading } = this.props;
    const { TextArea } = Input;
    const Panel = Collapse.Panel;
    const customPanelStyle = {
      background: '#f7f7f7',
      borderRadius: 4,
      marginBottom: 24,
      border: 0,
      overflow: 'hidden',
    };

    return (
      <PageHeaderLayout>
        <Row>
          <Col span={9}>
            <Card bordered={true} style={getScreenHeight()}>
              <MyTreeConfig
                dataSource={this.state.treeList}
                treeLoading={treeLoading}
                checkedKeys={this.state.selectedKeys}
                showDeleteModal={this.showDeleteModal}
                showEditorModal={this.showEditorModal}
                updateTreeMove={this.updateTreeMove}
                moveTree={this.moveTree}
                upData={this.upData}
                handleCheck={this.handleCheck}
                up
              />
            </Card>
          </Col>
          <Col span={15}>
            <Card bordered={true} style={getScreenHeight()}>
              <Collapse
                onChange={key => console.log(key)}
                bordered={false}
                defaultActiveKey={['1']}
              >
                <Panel header="查看版本号" key="1" style={customPanelStyle}>
                  <Spin tip="Loading..." spinning={this.props.tagLoading}>
                    <div>
                      {tags.map((tag, index) => {
                        const isLongTag = tag.length > 20;
                        const tagElem = (
                          <CheckableTag
                            key={index}
                            checked={tag.checked}
                            onChange={checked => {
                              this.setCheckedTag(checked, tag);
                            }}
                          >
                            {isLongTag ? `${tag.slice(0, 20)}...` : tag.content}
                          </CheckableTag>
                        );
                        return isLongTag ? (
                          <Tooltip title={tag} key={tag}>
                            {tagElem}
                          </Tooltip>
                        ) : (
                          tagElem
                        );
                      })}
                      {inputVisible && (
                        <Input
                          ref={this.saveInputRef}
                          type="text"
                          size="small"
                          style={{ width: 78 }}
                          value={inputValue}
                          onChange={this.handleInputChange}
                          onBlur={this.handleInputConfirm}
                          onPressEnter={this.handleInputConfirm}
                        />
                      )}
                      {!inputVisible && (
                        <Tag
                          onClick={this.showInput}
                          style={{ background: '#fff', borderStyle: 'dashed' }}
                        >
                          <Icon type="plus" /> 添加版本
                        </Tag>
                      )}
                    </div>
                  </Spin>
                </Panel>
              </Collapse>
              <Spin tip="Loading..." spinning={this.state.detailInfoLoading}>
                {this.state.detailInfo.map((d, i) => {
                  if (d.type === 1 || d.type === 2) {
                    return (
                      <div key={d.uniqueKey}>
                        <Row>
                          <Col span={20}>
                            <div style={{ textAlign: 'center', fontSize: '25px' }}>
                              <Katex value={d.viewContent} />
                            </div>
                          </Col>
                          <Col span={4}>
                            <a href="javascript:;" onClick={() => this.showEditorModal(d, '修改')}>
                              修改
                            </a>&nbsp;&nbsp;
                            <a href="javascript:;" onClick={() => this.showDeleteModal(d)}>
                              删除
                            </a>
                          </Col>
                        </Row>
                      </div>
                    );
                  } else if (d.type === 3) {
                    return (
                      <div key={d.uniqueKey}>
                        <div>
                          <Row>
                            <Col span={20}>
                              <div style={{ fontSize: '20px', fontWeight: 'bold' }}>知识点</div>
                            </Col>
                            <Col span={4}>
                              <a
                                href="javascript:;"
                                onClick={() => this.showEditorModal(d, '修改')}
                              >
                                修改
                              </a>&nbsp;&nbsp;
                              <a href="javascript:;" onClick={() => this.showDeleteModal(d)}>
                                删除
                              </a>
                            </Col>
                          </Row>
                        </div>
                        <div>
                          <Katex value={d.content} />
                        </div>
                      </div>
                    );
                  } else if (d.type === 4) {
                    return (
                      <div key={d.uniqueKey}>
                        <div>
                          <Row>
                            <Col span={20}>
                              <div style={{ fontSize: '20px', fontWeight: 'bold' }}>方法</div>
                            </Col>
                            <Col span={4}>
                              <a
                                href="javascript:;"
                                onClick={() => this.showEditorModal(d, '修改')}
                              >
                                修改
                              </a>&nbsp;&nbsp;
                              <a href="javascript:;" onClick={() => this.showDeleteModal(d)}>
                                删除
                              </a>
                            </Col>
                          </Row>
                        </div>
                        <div>
                          <Katex value={d.content} />
                        </div>
                        {/* <div hidden={!d.questionVoList || d.questionVoList.total === 0}>
                            <TreeConfigTable
                              dataSource={d.questionVoList ? d.questionVoList : []}
                              toolBar={toolBar}
                              deleteTableCell={this.deleteTableCell}
                              updateQuestions={this.updateQuestions}
                              pageChange={(page, size) => {
                                return this.commonPageChange(d, page, size);
                              }}
                              isCommon={true} />
                          </div> */}
                      </div>
                    );
                  } else if (d.type === 5) {
                    return (
                      <div key={i}>
                        <div>
                          <Row>
                            <Col span={20}>
                              <div style={{ fontSize: '20px', fontWeight: 'bold' }}>题型</div>
                            </Col>
                            <Col span={4}>
                              <a
                                href="javascript:;"
                                onClick={() => this.showEditorModal(d, '修改')}
                              >
                                修改
                              </a>&nbsp;&nbsp;
                              <a href="javascript:;" onClick={() => this.showDeleteModal(d)}>
                                删除
                              </a>
                            </Col>
                          </Row>
                        </div>
                        <div>
                          <Katex value={d.content} />
                        </div>

                        <Row>
                          <Col span={12}>
                            <strong>推荐例题</strong>
                          </Col>
                          <Col span={12} style={{ textAlign: 'right' }}>
                            <a
                              href="javascript:;"
                              onClick={() => this.showQuestionModal('liti', d.id)}
                            >
                              添加
                            </a>
                          </Col>
                        </Row>
                        <div className="coursewareTable">
                          <TreeConfigTable
                            dataSource={this.getQuestions(d.id, 'liti')}
                            toolBar={toolBar}
                            deleteTableCell={questionId => {
                              this.deleteTableCell(questionId, 'liti', d.id);
                            }}
                            updateQuestions={this.updateQuestions}
                            setDemoClick={this.setDemoClick}
                            moveQuestions={this.moveQuestions}
                            pageChange={(page, size) => {
                              return this.pageChange(d, page, size);
                            }}
                          />
                        </div>
                        <Row>
                          <Col span={12}>
                            <strong>推荐习题</strong>
                          </Col>
                          <Col span={12} style={{ textAlign: 'right' }}>
                            <a
                              href="javascript:;"
                              onClick={() => this.showQuestionModal('xiti', d.id)}
                            >
                              添加
                            </a>
                          </Col>
                        </Row>
                        <div className="coursewareTable">
                          <TreeConfigTable
                            dataSource={this.getQuestions(d.id, 'xiti')}
                            toolBar={toolBar}
                            deleteTableCell={questionId => {
                              this.deleteTableCell(questionId, 'xiti', d.id);
                            }}
                            updateQuestions={this.updateQuestions}
                            setDemoClick={this.setDemoClick}
                            moveQuestions={this.moveQuestions}
                            pageChange={(page, size) => {
                              return this.pageChange(d, page, size);
                            }}
                          />
                        </div>
                      </div>
                    );
                  }
                })}
                <Button type="primary" onClick={this.saveTreeConfig}>
                  保存
                </Button>
              </Spin>
              <br />
              {/* <Button type="primary">保存</Button> */}
            </Card>
          </Col>
        </Row>

        <Modal
          visible={this.state.deleteVisible}
          title="确定删除吗？"
          width="15%"
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          删除后，该项下属的节、知识点、方法、题型都会删除。题目也会失去对应的关系。
        </Modal>
        <Modal
          visible={this.state.editorVisible}
          title={this.state.editorTitle}
          width="60%"
          onOk={this.handleEditorOk}
          onCancel={this.handleEditorCancel}
        >
          <MyEditor
            toolBar={toolBar}
            value={this.state.currentEditorContent}
            id={'tree_' + this.state.currentAddNode.id}
            valueChange={e => {
              this.setState({ currentEditorContent: e });
            }}
          />
        </Modal>
        <QuestionModal
          visible={this.state.modalShow}
          questiontypeId={''}
          where={this.state.where}
          existIdStr={''}
          type={-1}
          onRef={ref => (this.questionModal = ref)}
          cancelModal={() => {
            this.setState({ modalShow: false });
          }}
          okModal={this.okModal}
        />
      </PageHeaderLayout>
    );
  }
}

export default TreeConfig;
